package com.sk.ccflower.server.lib.sockUtils.nio;

import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class SocketClient extends NioSession implements Runnable
{
    protected final String m_host;
    protected final int m_port;

    public SocketClient(String host, int port) throws Exception
    {
        super();

        m_host = host;
        m_port = port;
    }

    public SocketClient(String host, int port, NioSelector selector) throws Exception
    {
        this(host, port);

        if(selector!=null) m_selector = selector;
        else m_selector = new NioSelector();
    }

    public void connect() throws Exception
    {
        if(m_sc!=null) {
            try {
                m_sc.close();
            } catch (Exception ignore) {
            }
        }
        try{
            InetSocketAddress address=new InetSocketAddress( m_host , m_port );

            m_sc=SocketChannel.open( address );
            m_sc.configureBlocking( false );

            doConnectAction();
            
            if(m_selector!=null) registerHandler();
        } catch( Exception e ){
            m_log.debug(m_host + ":" + m_port + " doConnectAction()의 exception 발생으로 접속 종료", e);
            e.printStackTrace();
            try {
                m_sc.close();
            } catch(Exception ignore) {
            }
            throw e;
        }

        m_log.debug(m_sc.socket().getInetAddress().getHostAddress() + ":" + m_sc.socket().getPort() + " 접속 완료");
    }

    public void run()
    {
        try {
            m_selector.run();
        } catch(Exception e) {
            close();
            m_log.error("run error: " + e.getMessage(), e);
        } finally {
            close();
        }
    }

    /*
    public static void main(String[] argc)
    {
        try {
            SocketClient client = new SocketClient("localhost", 9000);
            client.connect();
            client.run();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    */
}
